package advanced.network.basic_servlet;

import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;

public class WebApp {
    private static WebContext context;

    static {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        WebHandler webHandler;
        try {
            SAXParser saxParser = factory.newSAXParser();
            File xml = new File(Thread.currentThread().getContextClassLoader().getResource("advanced/network/basic_servlet/web.xml").toURI());
            webHandler = new WebHandler();
            saxParser.parse(xml, webHandler);
            context = new WebContext(webHandler.getEntitis(), webHandler.getMappings());

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public static Servlet getServletFromUrl(String action) {
        //模仿浏览器请求了/reg这个action
        String claName = context.getClz(action);
        Class clz = null;
        Servlet servlet = null;
        try {
            clz = Class.forName(claName);
            servlet = (Servlet) clz.getConstructor().newInstance();
        } catch (Exception e) {
            System.out.println("没有注册相应的servlet");
        }
        return servlet;
    }

    public static void release(Closeable... args) {
        for (Closeable arg : args) {
            if (arg != null) {
                try {
                    arg.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
